package web;


import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import dao.FitsDao;

import model.FitsFile;
import model.FitsFileList;


@SuppressWarnings("serial")
public class ScanServlet extends HttpServlet{
	@SuppressWarnings("unchecked")
	
	private static Logger logger = Logger.getLogger(ScanServlet.class);
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
    	
		BasicConfigurator.configure();
		String survey = request.getParameter("survey");
		String folder = request.getParameter("location");
logger.info("Survey is:"+survey);
logger.info("Folder is:"+folder);
		
		int lOfF = folder.length();
		String lastChar = folder.substring(lOfF-1,lOfF);
		
logger.info("Last character is: "+lastChar);		
logger.info("Operating System is: "+java.lang.System.getProperty("os.name"));		

		//on unix
		if(java.lang.System.getProperty("os.name").equals("Unix")||java.lang.System.getProperty("os.name").equals("Linux")){
			if(!(lastChar.equals("/"))){
				folder=folder+"/";			//add / to the end of the folder name if it's not already there
logger.info("Folder name is:"+folder);
			}
		}
		if(java.lang.System.getProperty("os.name").equals("Windows Vista")){
			if(!(lastChar.equals("\\"))){
				folder=folder+"\\";
logger.info("Folder name is:"+folder);
			}
		}
		
//System.out.println(survey);
//System.out.println(folder);
	
	// make a list from this location
		FitsFileList ffListObj = new FitsFileList();
		ffListObj.makeListFromFolder(folder, survey);
		ArrayList<FitsFile> ffList = ffListObj.getListOfFF();
		Iterator<FitsFile> itr = ffList.iterator();
//		while(itr.hasNext()){
//			FitsFile ff = itr.next();
//			String filename = ff.getFilename();
//			String crType1 = ff.getCtype1();
//			double crVal1 = ff.getCrval1();
//			String survey1 = ff.getSurvey();
//			System.out.println(filename+ " "+ crType1+" "+crVal1+ " "+ survey1);
//	// TODO Auto-generated catch block
//	
//		}
	// return the user to the scan page
		FitsDao fdao = new FitsDao();
		try {
			fdao.saveFilesToDB(ffList);
			ffList = fdao.getListOfFitsFiles();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		Iterator<FitsFile> itr2 = ffList.iterator();
//		while(itr.hasNext()){
//			FitsFile ff = itr2.next();
//System.out.println(ff.getFilename());
//		}
		
		response.sendRedirect("jsp/scan.jsp");
	}
}
